package com.dynamic.mybatis.config;


import com.alibaba.fastjson.JSON;
import com.dynamic.mybatis.core.builder.DynamicMapperAdapterBuilder;
import com.dynamic.mybatis.core.metadata.DynamicScriptMappedStatement;
import com.dynamic.mybatis.mapper.CommonMapper;
import com.dynamic.mybatis.vo.DynamicSqlVo;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Component
public class DynamicMybatisSQLHandle  {
    private static Logger logger = LoggerFactory.getLogger(DynamicMybatisSQLHandle.class);

    @Autowired
    SqlSessionTemplate sqlSessionTemplate;
    @Autowired
    CommonMapper commonMapper;


    /**  动态sql初始化  */
    public  void dynamicMappedStatementInit(){
        List<DynamicSqlVo> dynamicSqlVos = commonMapper.queryDynamicSQLListToInit();
        if(CollectionUtils.isEmpty(dynamicSqlVos)){
            logger.info("dynamicSql init empty.");
            return;
        }
        for (DynamicSqlVo sqlVo : dynamicSqlVos){
            try {
                new DynamicMapperAdapterBuilder(sqlSessionTemplate.getConfiguration())
                        .parser( new DynamicScriptMappedStatement.Builder()
                                .setResultType(sqlVo.getResultType())
                                .setResultMap(sqlVo.getResultMap())
                                .setId(sqlVo.getCode())
                                .setSqlCommandType(sqlVo.getOperateType())
                                .setMappedStatement(sqlVo.getDynamicSql())
                                .setReturnType(sqlVo.getReturnType()).builder()
                        );
            }catch (Exception e){
                logger.error("dynamicSql init error. "+ JSON.toJSONString(sqlVo),e);
            }
        }
        logger.info("dynamicSql init finish. size [{}]",dynamicSqlVos.size());
    }
}
